package logbrowse;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LogModel {
	public static LogModel createEmpty() {
		return new LogModel();
	}
	
	public static LogModel openFile(File file) throws IOException {
		LogModel ret = new LogModel();
		ret.source = file;
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(file));
			String date = null;
			boolean forced = false;
			String msg = null;
			StringBuilder text = new StringBuilder();
			while (true) {
				String line = in.readLine();
				if (line == null) break;
				
				if (line.startsWith("--SEND ")) {
					if (line.startsWith("--SEND at ")) {
						addEntry(ret, date, forced, msg, text);
						date = line.substring(10);
						forced = false;
						msg = null;
						text = new StringBuilder();
					} else if (line.startsWith("--SEND force ")) {
						addEntry(ret, date, forced, msg, text);
						date = line.substring(13);
						forced = true;
						msg = null;
						text = new StringBuilder();
					} else if (line.startsWith("--SEND msg ")) {
						msg = line.substring(11);
					}
				} else {
					text.append(line);
					text.append("\n");
				}
			}
			addEntry(ret, date, forced, msg, text);
			in.close();
			return ret;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e2) { }
			}
		}
	}
	
	private static void addEntry(LogModel model, String date, boolean forced,
			String msg, StringBuilder text) {
		if (date != null) {
			String textStr = text.toString();
			int sz = model.entries.size();
			String prev = sz == 0 ? "" : model.entries.get(sz - 1).getText();
			int mods = LogEntryDiff.compute(prev, textStr).getDistance();
			LogEntry entry = new LogEntry(sz, date, forced,
					msg, text.toString(), mods);
			model.entries.add(entry);
		}
	}
	
	private File source;
	private ArrayList<LogEntry> entries;
	private List<LogEntry> entriesView;
	
	private LogModel() {
		source = null;
		entries = new ArrayList<LogEntry>();
		entriesView = Collections.unmodifiableList(entries);
	}
	
	public File getSourceFile() {
		return source;
	}
	
	public List<LogEntry> getEntries() {
		return entriesView;
	}
	
	public int getEntryCount() {
		return entries.size();
	}
	
	public LogEntry getEntry(int index) {
		return entries.get(index);
	}
}
